package com.fgw.realm;

import com.fgw.common.Const;
import com.fgw.dao.TeacherMapper;
import com.fgw.pojo.Teacher;
import com.fgw.service.ITeacherlibService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * Created by lyj on 2017/9/22.
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private TeacherMapper teacherMapper;


    // 验证当前登录的用户，获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String tuser = (String) token.getPrincipal(); // 获取用户名
        Teacher teacher = teacherMapper.getByUsername(tuser);
        if(teacher != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(teacher.getTuser(),teacher.getTpassword(), "myRealm");
            return authcInfo;
        } else {
            return null;
        }
    }

    // 为当前登陆成功的用户授予权限和角色，已经登陆成功了
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        String tuser = (String) principals.getPrimaryPrincipal(); //获取用户名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //authorizationInfo.setRoles(teacherMapper.getRoles(tuser));
        authorizationInfo.setStringPermissions(teacherMapper.getPermissions(tuser));
        return authorizationInfo;
    }
}
